package cn.xuqiudong.rpc.registry.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

/**
 * 描述: Curator的TreeCacheListener的实现类，监听子节点变化
 * @author Vic.xu
 * @date 2022-02-17 10:28
 */
public class XqdCuratorWatcherImpl implements CuratorWatcher, TreeCacheListener {

    private CuratorFramework client;
    private volatile ChildListener childListener;
    private String path;

    public XqdCuratorWatcherImpl(CuratorFramework client, ChildListener childListener, String path) {
        this.client = client;
        this.childListener = childListener;
        this.path = path;
    }

    @Override
    public void process(WatchedEvent event) throws Exception {

        if (event.getType() == Watcher.Event.EventType.None) {
            return;
        }
        if (childListener != null) {
            childListener.childChanged(path, client.getChildren().usingWatcher(this).forPath(path));
        }
    }

    @Override
    public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent event) throws Exception {

        if (childListener == null) {
            return;
        }
        TreeCacheEvent.Type type = event.getType();
        //暂只在 新增 修改和移除节点的时候做通知
        switch (type) {
            case NODE_ADDED:
            case NODE_UPDATED:
            case NODE_REMOVED:
                childListener.childChanged(path, client.getChildren().usingWatcher(this).forPath(path));
            default:
                break;
        }

    }

    /**
     * 取消订阅， 监听器置为空
     */
    public void unwatch() {
        this.childListener = null;
    }
}
